package com.cpip.user.config;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Component
public class JwtUtil {

    private static final String CLAIM_KEY_USERNAME="sub";
    private static final String CLAIM_KEY_CREATED="created";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    //根据用户信息生成token
    public String generateToken(String jsonInformation){
        Map<String,Object> claims=new HashMap<>();
        claims.put("jsonInformation",jsonInformation);
        claims.put("createTime",new Date());
        return generateToken(claims);
    }

    //从token中获取登录信息
    public String getInformationFromToken(String token){
        String jsonInformation;
        Claims claims=getClaimsFromToken(token);
        if (claims.containsKey("jsonInformation")){
            jsonInformation = (String)claims.get("jsonInformation");
        }else{
            jsonInformation=null;
        }
        return jsonInformation;
    }

    //判断token是否失效
    public boolean validateToken(String token,Object information){
        Object tokenInformation= getInformationFromToken(token);
        return tokenInformation.equals(information) && !isTokenExpired(token);
    }


    //刷新token
    public String refreshToken(String token){
        Claims claims=getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }

    //判断token是否可以被刷新
    public boolean canRefresh(String token){
        return !isTokenExpired(token);
    }

    //验证token是否失效
    private boolean isTokenExpired(String token) {
        Date expiredDate=getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }


    //从token中获取失效时间
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    //从token中获取荷载
    private Claims getClaimsFromToken(String token) {
        Claims claims=null;
        try {
            claims=Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;
    }

    //根据荷载生成JWT token
    private String generateToken(Map<String,Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    //生成token失效时间
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis()+expiration*1000);
    }

}